import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Navigator, Image} from '@tarojs/components';
import {AtButton, AtIcon, AtModal, AtModalAction, AtModalContent, AtModalHeader} from 'taro-ui';
import {Wallet as WalletData} from '../../utils/server.interface';
import {http} from '../../utils/http';
import {CONTENT_PLAT_QR, RESOURCE_URL, WALLET, WITH_DRAW} from '../../constants/api';
import {user} from '../../utils/user.service'
import {platform} from "../../utils/platform-settting.service";
import {vcmonitor} from "../../utils/tools";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {h5Wx} from "../../utils/h5.service";
import './wallet.scss';

type PageState = {
  userIdentity: any
  wallet: WalletData
  withdraw: number
  submitting: boolean
  uuid: string
  isSeller: boolean
  payMethod: number
  modalShow: boolean
  qrImg: any
  qrImgDescribe: any
}

export default class Wallet extends Component {
  state: PageState = {
    userIdentity: false,
    wallet: {
      allBalance: 0,
      unWithdrawBalance: 0,
      withdrawBalance: 0,
      sellerWithdrawMinimumAmount: 0
    },
    isSeller: false,
    withdraw: 0,
    submitting: false,
    uuid: '',
    payMethod: 0,
    modalShow: false,
    qrImg: '',
    qrImgDescribe: ''
  }

  async componentDidShow() {
    vcmonitor(this)
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const isLogin = await user.checkLogin()
    this.setState({
      uuid: Taro.getCurrentInstance().router.params.uuid,
      isSeller: Taro.getCurrentInstance().router.params.isSeller,
      payMethod: platform.info.payMethod
    })
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    const userIdentity = await user.getUserData()
    const wallet = await http.get<Wallet>(WALLET, {})
    if (wallet) {
      this.setState({wallet})
    }
    if (!userIdentity) {
      return
    }
    this.onOpenmodel()
    this.setState({userIdentity})
  }

  inputChange(value) {
    this.setState({withdraw: Number(value.detail.value)})
  }

  submit() {
    this.setState({submitting: true}, async () => {
      if (this.state.wallet.withdrawBalance < this.state.withdraw) {
        Taro.showToast({title: '超过最大提现金额', icon: 'none'})
        this.setState({submitting: false})
      } else if (this.state.withdraw == 0) {
        Taro.showToast({title: '请输入金额', icon: 'none'})
        this.setState({submitting: false})
      } else if (this.state.withdraw < this.state.wallet.sellerWithdrawMinimumAmount) {
        Taro.showToast({title: '最低提现' + this.state.wallet.sellerWithdrawMinimumAmount + '元', icon: 'none'})
        this.setState({submitting: false})
      } else {
        const ret = await http.postCondition(WITH_DRAW, {amount: this.state.withdraw, uuid: this.state.uuid})
        if (ret) {
          Taro.showToast({title: '提现成功！请耐心等待审核！', icon: 'none'})
        }
        this.setState({submitting: false})
      }
    })
  }

  cashOut() {
    const that = this
    Taro.navigateTo({
      url: '/distributor/wallet/cash?uuid=' + that.state.uuid
    })
  }

  stop(e) {
    e.stopPropagation()
  }

  async onOpenmodel(btn) {
    const res = await http.HGet(CONTENT_PLAT_QR, {send_type: 6});
    this.setState({qrImg: res.data.code, qrImgDescribe: res.data.code_describe})
    if (btn) {
      this.setState({modalShow: true})
    }
  }

  handleCancel() {
    this.setState({modalShow: false})
  }

  handleClose() {
    this.setState({modalShow: false})
  }

  getDisabledStatus(wallet, userIdentity) {
    if (wallet.withdrawBalance < wallet.sellerWithdrawMinimumAmount) {
      return true
    }
    return !!userIdentity.isBlackList;

  }

  render() {
    const {wallet, modalShow, qrImg, qrImgDescribe, userIdentity} = this.state
    return (
      <View className='wallet-root'>
        <GzhAuth />
        <View className='head'>
          <Image className='iconImg' src={RESOURCE_URL + "/resources/weapp/images/cashout-icon.png"} mode='aspectFill' />
          <View className='title'>可提金额</View>
          <View className='num total'><Text>￥</Text>{wallet.withdrawBalance}</View>
        </View>
        <View className='btn-box tadpole'>
          <View className='btn'>
            <View
              onClick={this.cashOut.bind(this)}
              className={`btn-style ${this.getDisabledStatus(wallet, userIdentity) && 'withdraw-btn'}`}
              style={`background-color: ${process.env.mainColor};font-size:18px;`}
            >提现</View>
          </View>
          <Navigator className='btn' url='/distributor/wallet/recharge'>
            <AtButton type='secondary'>充值</AtButton>
          </Navigator>
        </View>
        <View className='tips-box'>
          <Navigator url='/distributor/wallet/record' className='tips-item' hoverClass='none'>
            <AtIcon value='clock' size='16' color='#666'></AtIcon>
            <Text>交易记录</Text>
          </Navigator>
          <Navigator
            url={"/distributor/wallet/rule?min=" + wallet.sellerWithdrawMinimumAmount + "&f=" + wallet.sellerWithdrawRate}
            className='tips-item' hoverClass='none'
          >
            <AtIcon value='alert-circle' size='16' color='#666'></AtIcon>
            <Text>规则说明</Text>
          </Navigator>
          {qrImg && qrImg !== 'variable_code_close' &&
            <View className='tips-item tips-item-ti' hoverClass='none' onClick={this.onOpenmodel.bind(this, true)}>
              <Image src='https://resource.ivcheng.com/upload/file/04e9b208c941453f9205d9e80ec3356b.png'
                className='tips-item-ti-img'
              ></Image>
              <Text>提现审核</Text>
            </View>}
        </View>
        <AtModal className='modal_concatWx' isOpened={modalShow} onClose={this.handleCancel.bind(this)}>
          <AtModalHeader>{qrImgDescribe}</AtModalHeader>
          <AtModalContent>
            {qrImg && qrImg !== 'variable_code_close' && <Image
              mode='aspectFill'
              style='width: 120px;height: 120px;'
              src={qrImg}
            />}
          </AtModalContent>
          <AtModalAction>
            {process.env.TARO_ENV === 'h5' && <Text className='modal_txt'>
              您的提现申请已收到<br />请添加财务微信发送“我要提现”
            </Text>}
            {process.env.TARO_ENV !== 'h5' && <View className='modal_txt'>
              <View>您的提现申请已收到</View>
              <View>请添加财务微信发送“我要提现”</View>
            </View>}
          </AtModalAction>
        </AtModal>
      </View>
    );
  }
}
